//
// Created by zhfayuan on 2021/6/9.
//

#include <iostream>
#include "RelayTerminal.h"

RelayTerminal::RelayTerminal(RelayTermHandler *t,RelayStreamHandler *m)
:_tHandler(t),_mHandler(m)
{
    _inner =  std::make_shared<CSDMedia>(this,0,TERM_TYPE_GB28181_SVR);
}

RelayTerminal::~RelayTerminal()
{
    disconnect();
    _inner.reset();
    _inner = nullptr;
}

bool RelayTerminal::connect(uint32_t gid, std::string ip, uint32_t port)
{
    if(!_inner || !_inner.get())
        return false;
    return (_inner->IFace_Online(ip.c_str(),port,USER_TYPE_AV_RECV_ONLY,gid,0)  == RET_SUCCESS ? true:false);
}
void RelayTerminal::disconnect()
{
    if(!_inner || !_inner.get())
        return;
    _inner->IFace_Offline();
}

void RelayTerminal::OnSystemExit(UINT unExitCause)
{
    if(!_tHandler)
        return;
    _tHandler->onRelayConnectionLost();
}

bool RelayTerminal::onPosition(uint64_t room)
{
    if(_inner->IFace_OnPosition(room,USER_TYPE_AV_RECV_ONLY,AUDIO_CODEC_NONE,VIDEO_CODEC_NONE,0,0,0,
                                    nullptr,0,0) == RET_SUCCESS){
        _inner->IFace_SetAvDownMasks(room,0x01,0x1);
        return  true;
    }
    return  false;
}
void RelayTerminal::offPosition(uint64_t room)
{
    if (_inner)
        _inner->IFace_OffPosition(room);
}

void RelayTerminal::OnRemoteVideo(UINT64 unRoomId,BYTE byCodec,BYTE byIndex, BYTE* data, UINT unLen, UINT unPTS, VideoFrameInfo tFrameInfo)
{
    if(!_mHandler)
        return;
    _mHandler->onRelayVideoData(unRoomId,(char*)data,unLen,unPTS,tFrameInfo.bKeyFrame,VIDEO_CODEC_H265 == byCodec);
}
void RelayTerminal::OnRemoteAudio(UINT64 unRoomId,BYTE byCodec,BYTE byIndex, BYTE* data, UINT unLen, UINT unPTS, AudioFrameInfo tFrameInfo)
{
    if(!_mHandler)
        return;
    _mHandler->onRelayAudioData(unRoomId,(char*)data,unLen,unPTS);
}

void RelayTerminal::OnRemoteCmd(USHORT cmd,USHORT subCmd,BYTE*data,UINT unLen)
{

}
void RelayTerminal::OnKeyNegotiated(UINT unKeyToken,BYTE*key,UINT unKeyLen)
{

}
void RelayTerminal::OnStreamDecryptFailed(UINT64 unRoomId, BYTE byIndex)
{

}
void RelayTerminal::OnFileExtractResult(std::string strPath,BYTE toEnd,UINT unExitCause)
{

}
void RelayTerminal::OnFileExtractProgress(std::string strPath,BYTE percent)
{

}

void RelayTerminal::OnAVProviderOnPosition(UINT64 unUid,UINT64 unRoomId,BYTE byAvIndex)
{
    if(!_mHandler)
        return;
    _mHandler->onRelayProviderOnPosition(unUid,unRoomId,byAvIndex);
}
void RelayTerminal::OnAVProviderOffPosition(UINT64 unUid,UINT64 unRoomId,BYTE byAvIndex)
{
    if(!_mHandler)
        return;
    _mHandler->onRelayProviderOffPosition(unUid,unRoomId,byAvIndex);
}